/**
 * 
 */
package net.xfok.http.client;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.util.Log;

/**
 * @author howard
 *
 */
public class HttpClient {
	
	private static final String TAG="HttpClient";
	private static final int BUFFER_SIZE=4096;
	
	/**
	 * Request
	 * @param url request url
	 * @param charset html's charset
	 * @return
	 */
	public String request(String url,String charset){
		try {
			URL uri = new URL(url);
			HttpURLConnection con = (HttpURLConnection) uri.openConnection();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					con.getInputStream(), charset));
			StringBuffer b=new StringBuffer(BUFFER_SIZE);
			String line;
			while ((line = reader.readLine()) != null) {
				b.append(line);
				b.append("\r\n");
			}
			return b.toString();
		} catch (FileNotFoundException ex) {
			Log.i(TAG,"NOT FOUND:" + url );
			return null;
		} catch (ConnectException ex) {
			Log.i(TAG,"Timeout:" + url);
			return null;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}
	
	/**
	 * get input stream from http connection
	 * 
	 * @return http inputstream
	 * @throws IOException 
	 */
	public InputStream request(String url){
		InputStream inputStream = null;
		try{
			URL uri = new URL(url.replace(" ", "%20"));
			HttpURLConnection urlConnection = (HttpURLConnection)uri.openConnection();
			try{
				int responseCode = urlConnection.getResponseCode();
				if (responseCode == HttpURLConnection.HTTP_OK) {
					inputStream = urlConnection.getInputStream();
				} else {
					inputStream = null;;
				}
			}catch(Exception e){
				e.printStackTrace();
			}	
		}catch(Exception e){
			e.printStackTrace();
		}
		return inputStream;
	}
	
	/**
	 * Get Method
	 * @param url request url
	 * @return
	 */
	public String doGet(String url){
		String html=null;
        HttpGet request = new HttpGet(url);  
        org.apache.http.client.HttpClient httpClient = new DefaultHttpClient();  
        try {  
            HttpResponse response = httpClient.execute(request);  
            if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){  
                html= EntityUtils.toString(response.getEntity());  
            }
        } catch (ClientProtocolException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();      
        } catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        return html;
	}
	
	/**
	 * Post Method
	 * @param url request url
	 * @param parms parameters
	 */
	public String doPost(String url,Map parms){
		return doPost(url, parms, "UTF-8");
	}
	
	/**
	 * Post Method
	 * @param url request url
	 * @param parms parameters
	 * @param charset parameters's encoding
	 * @return
	 */
	public String doPost(String url,Map parms,String charset){
		String html=null;
		// 构造HttpClient的实例
		org.apache.http.client.HttpClient httpClient = new DefaultHttpClient();
		// 创建P方法的实例
		HttpPost request = new HttpPost(url);
		List<NameValuePair> params = new ArrayList<NameValuePair>(); 
		// 填入各个表单域的值
		if(parms!=null){
			Iterator it = parms.entrySet().iterator();
			int i=0;
			while (it.hasNext()) {
				Map.Entry entry = (Map.Entry) it.next();
				Object key = entry.getKey();
				Object value = entry.getValue();
				params.add(new BasicNameValuePair(key.toString(),value.toString()));
				i++;
			}
		}
		try {  
            HttpEntity entity = new UrlEncodedFormEntity(params, charset);  
            request.setEntity(entity);  
            HttpResponse response = httpClient.execute(request);  
            if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){  
                html= EntityUtils.toString(response.getEntity());  
            }
        } catch (UnsupportedEncodingException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (IOException e) {   
            e.printStackTrace();  
        }  
        return html;
	}
	
}
